package service

import (
	"context"
	"net/http"
	"sync"

	"sieve_admin_server_userpass/pkg/app"
	"sieve_admin_server_userpass/pkg/log"
	"sieve_admin_server_userpass/pkg/util/net"
)

var (
	httpPort = 0
	httpLock = sync.Mutex{}
)

func AddHttpHandler(path string, handler http.HandlerFunc) error {
	port, err := getHttpPort()
	if err != nil {
		return err
	}
	http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
		defer log.RecoverPanic()
		handler(w, r)
	})
	return addHttpHandler(path, port)
}

func getHttpPort() (int, error) {
	httpLock.Lock()
	defer httpLock.Unlock()
	if httpPort == 0 {
		l, p, err := net.GetValidListener("", 9000, 9999)
		if err != nil {
			return 0, err
		}
		httpPort = p

		// http.HandleFunc("/", http.NotFound)

		sv := &http.Server{}
		sv.SetKeepAlivesEnabled(false)
		app.AsyncSafe(func() {
			<-app.CTX.Done()
			sv.Shutdown(context.Background())
		})
		app.AsyncSafe(func() {
			log.Info(sv.Serve(l))
		})
	}
	return httpPort, nil
}
